#include "mystdio.h"
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>

static MyFile* BuyFile(int fd, int flag)
{
    MyFile * f= (MyFile*)malloc(sizeof(MyFile));
    if(f == NULL)
    {
        return NULL;
    }
    f->bufferlen = 0;
    f->fileno = fd;
    f->flag = flag;
    f->flush_method = LINE_FLUSH;
    memset(f->outbuffer, 0, sizeof(f->outbuffer));
    return f;
}

MyFile *MyFopen(const char *path, const char* mode)
{
    int fd = -1;
    int flag = 0;
    if(strcmp(mode, "w") == 0)
    {
        flag = O_CREAT|O_WRONLY|O_TRUNC;
        fd = open(path, flag, 0666);
    }
    else if(strcmp(mode, "r") == 0) 
    {
        flag = O_RDONLY;
        open(path, flag);
    }
    else if(strcmp(mode, "a") == 0)
    {
        flag = O_CREAT|O_WRONLY|O_APPEND;
        open(path, flag, 0666);
    }
    else
    {
        //......
    }

    //得到文件描述符⬆
    if(fd < 0)
    {
        return NULL;
    }
    
    //创建文件
    MyFile* f = BuyFile(fd, flag);

    return f;
}
void MyFclose(MyFile* file)
{
    if(file->fileno < 0) return;
    MyFFlush(file);
    close(file->fileno);
}
int MyFwrite(MyFile* file, void *str, int len)
{
    //写入就是拷贝
    memcpy(file->outbuffer+file->bufferlen, str, len);
    file->bufferlen  += len;
    if((file->flush_method & LINE_FLUSH ) && (file->outbuffer[file->bufferlen - 1] == '\n'))        
    {
        //行刷新
        MyFFlush(file);
    }
    return 0;
}
void MyFFlush(MyFile* file)
{
    if(file->bufferlen <= 0)
    {
        return;
    }
    //将缓冲区里的数据全都写到前面创建的文件里
    int n = write(file->fileno, file->outbuffer, file->bufferlen);
    file->bufferlen = 0;
}
